package com.wntms.auser.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wntms.auser.dao.MenuDao;
import com.wntms.auser.dao.RoleMenuDao;
import com.wntms.auser.dao.UserDao;
import com.wntms.auser.dao.UserRoleDao;
import com.wntms.auser.pojo.Menu;
import com.wntms.auser.pojo.RoleMenu;
import com.wntms.auser.pojo.User;
import com.wntms.auser.pojo.UserRole;
import com.wntms.auser.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuDao menuDao;
    @Autowired
    private RoleMenuDao roleMenuDao;
    @Autowired
    private UserRoleDao userRoleDao;
    @Autowired
    private UserDao userDao;

    public List<Menu> getMenusByUser() {
        // 获取当前用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String account = authentication.getPrincipal().toString();

        QueryWrapper qw3 = new QueryWrapper<>();
        qw3.eq("account", account);
        Integer uid = userDao.selectOne(qw3).getId();


        // 获得当前用户对应的角色的 id 列表
        QueryWrapper qw1 = new QueryWrapper<>();
        qw1.eq("uid", uid);
        Integer rid = userRoleDao.selectOne(qw1).getRid();


        // 查询出这些角色对应的所有菜单项
        QueryWrapper qw2 = new QueryWrapper<>();
        qw2.eq("rid", rid);
        qw2.orderByAsc("mid");
        List<RoleMenu> menuIds = roleMenuDao.selectList(qw2);
        List<Menu> menus = new ArrayList<>();
        for (RoleMenu menuId : menuIds) {
            QueryWrapper qw = new QueryWrapper<>();
            qw.eq("id",menuId.getMid());
            Menu menu = menuDao.selectOne(qw);
            menus.add(menu);
        }

        handleMenus(menus);
        return menus;
    }

    public void handleMenus(List<Menu> menus) {

        menus.forEach(m -> {
            QueryWrapper qw = new QueryWrapper<>();
            qw.eq("parent_id",m.getId());
            List<Menu> children = menuDao.selectList(qw);
            m.setChildren(children);
        });

        menus.removeIf(m -> m.getParentId() != 0);
    }

}
